using System;
using SCore.Editor.BuildPackage.Player;
using UnityEditor;
using BuildAddressable = SCore.Editor.BuildPackage.Addressable.BuildAddressable;

namespace SCore.Editor.BuildPackage
{
    public class BuildPackage
    {
        private static void AnalysisCommandLineArgs(string[] args)
        {
            if (null == args || 0 >= args.Length)
            {
                "[BuildPackage]================args is null or its length is 0".Log();
                return;
            }

            string channel = string.Empty;
            string release = string.Empty;
            $"[AnalysisCommandLineArgs]======={string.Join(",", args)}".Log();
            foreach (var arg in args)
            {
                if (arg.StartsWith("channel"))
                {
                    channel = arg.Split('-')[1];
                }
                else if (arg.StartsWith("release"))
                {
                    release = arg.Split('-')[1];
                }
            }

            //查找参数 channel 和 platform
            var buildConfig = BuildPipelineConfig.Instance;
            var sBuildChannel = buildConfig.GetSBuildChannelData(channel);
            var sBuildTarget = buildConfig.GetSBuildTargetData(release);
            if (sBuildChannel == null || sBuildTarget == null)
            {
                $"sBuildData is Empty {channel}".Error();
                return;
            }

            // 先做一些高优先级的
            foreach (var arg in args)
            {
                if (arg.StartsWith("release"))
                {
                    buildConfig._release = arg.Split('-')[1];
                    // init
                    if (buildConfig._release == BuildPipelineUtils.STargetType.Release)
                    {
                        buildConfig._withDebugLog = false;
                    }
                    else
                    {
                        buildConfig._withDebugLog = true;
                    }

                    break;
                }
            }

            foreach (var arg in args)
            {
                if (arg.StartsWith("version"))
                {
                    buildConfig._version = arg.Split('-')[1];
                }
                else if (arg.StartsWith("bundleVersionCode"))
                {
                    buildConfig._bundleVersionCode = arg.Split('-')[1];
                }
                else if (arg.StartsWith("sdkEnv"))
                {
                    var test = arg.Split('-')[1];
                    buildConfig._sdkEnv = test == "1";
                }
                else if (arg.StartsWith("firebase_test"))
                {
                    var test = arg.Split('-')[1];
                    buildConfig._fireBaseTest = (test == "1" || test == "true");
                }
                else if (arg.StartsWith("withDebugLog"))
                {
                    var test = arg.Split('-')[1];
                    buildConfig._withDebugLog = test == "1";
                }
                else if (arg.StartsWith("injectEnv"))
                {
                    buildConfig._injectEnv = arg.Split('-')[1];
                }
                else if (arg.StartsWith("opExport"))
                {
                    var test = arg.Split('-')[1];
                    buildConfig._opExport = Enum.Parse<BuildPipelineConfig.SBuildOp>(test);
                }
                else if (arg.StartsWith("exportAAB"))
                {
                    var test = arg.Split('-')[1];
                    buildConfig._isExportAAb = test == "1";
                }
                else if (arg.StartsWith("timeOffset"))
                {
                    buildConfig._timeOffset = int.Parse(arg.Split('-')[1]);
                }
            }

            BuildPipelineConfig.Instance.BindBuilding(sBuildChannel);
            BuildPipelineConfig.Instance.BindBuilding(sBuildTarget);
        }

        public static void BuildJenkins()
        {
            BuildPipelineUtils.SetRemoteLoadPathForJenkinsByCode();
            var args = Environment.GetCommandLineArgs();
            AnalysisCommandLineArgs(args);
            SBuild();
        }

        private static bool Check()
        {
            var sbuildConfig = BuildPipelineConfig.Instance;
            if (sbuildConfig == null)
            {
                "BuildPipelineConfig is Empty Please to Create".Error();
                return false;
            }

            var sBuildChannel = BuildPipelineConfig.Instance._buildChannel;
            if (sBuildChannel == null)
            {
                "sBuildChannel is Empty Please to Create".Error();
                return false;
            }

            var sBuildTarget = BuildPipelineConfig.Instance._buildTarget;
            if (sBuildTarget == null)
            {
                "sBuildTarget is Empty Please to Create".Error();
                return false;
            }

            if (EditorUserBuildSettings.activeBuildTarget != sBuildChannel.GetBuildTarget())
            {
                if (!EditorUserBuildSettings.SwitchActiveBuildTarget(
                        UnityEditor.BuildPipeline.GetBuildTargetGroup(sBuildChannel.GetBuildTarget()),
                        sBuildChannel.GetBuildTarget())) throw new Exception("Switch BuildTarget Failure.");
                if (string.IsNullOrEmpty(BuildPipelineConfig.Instance.GetOutPutPath()[0]))
                    throw new ArgumentException();
            }

            return true;
        }

        public static void SBuild()
        {
            if (Check())
            {
                int timestamp = (int)BuildPipelineUtils.GetTimeSpan().TotalSeconds;
                BuildPipelineConfig.Instance._version =
                    BuildPipelineUtils.GenerateTimeStampVersion(BuildPipelineConfig.Instance._version,
                        timestamp + BuildPipelineConfig.Instance._timeOffset);
                //构建
                BuildPipelineConfig.Instance._buildChannel.SBuildPlatform(); //平台
                BuildPipelineConfig.Instance._buildTarget.SBuild(); //target
                BuildPipelineConfig.Instance._buildChannel.SBuild(); //channel

                if (BuildPipelineConfig.Instance._opExport == BuildPipelineConfig.SBuildOp.Addressable)
                {
                    BuildPipelineUtils.CopyAboutAssets(BuildPipelineConfig.Instance._buildChannel.GetBuildTarget(),
                        true);
                    BuildAddressable.SBuild();
                }
                else
                {
                    //addressable 在构建Player的时候会自动执行一次BuildPlayerContent 为了屏蔽自动构建需要对BuildAddressablesOverride进行覆盖
                    AddressablesPlayerBuildProcessor.BuildAddressablesOverride +=
                        BuildAddressable.BuildAddressablesOverride;

                    BuildPipelineUtils.CopyAboutAssets(BuildPipelineConfig.Instance._buildChannel.GetBuildTarget(),
                        false);
                    BuildAddressable.SBuild();
                    BuildPlayer.SBuild();
                    //释放
                    AddressablesPlayerBuildProcessor.BuildAddressablesOverride -=
                        BuildAddressable.BuildAddressablesOverride;
                }
            }
        }
    }
}